package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.config.AliyunSmsUtil;
import com.itheima.reggie.entify.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R send(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StrUtil.isEmpty(phone)) {
            return R.error("手机号不能为空！");
        }
        //设置六位验证码
        String code = RandomUtil.randomNumbers(6);

        //假装发送六位验证码
        AliyunSmsUtil.sendSms2(phone, code);

        session.setAttribute(phone, code);

        return R.success("验证码发送成功");
    }

    /**
     * 前端登录
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> user, HttpSession session) {
        String phone = user.get("phone");
        String code = user.get("code");
        if (StrUtil.isEmpty(phone) || StrUtil.isEmpty(code)) {
            return R.error("手机号或验证码不能为空");
        }
        //获取服务器中存储的真实验证码
        String realCode = (String) session.getAttribute(phone);
        //验证码用一次就要销毁掉
        session.removeAttribute(phone);
        if (code.equals(realCode)) {
            //登录成功
            //判断手机号是否已经注册，如果没有注册，则注册的user表中
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone, phone);
            User one = userService.getOne(qw);
            if (one == null) {
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            //将数据存储到session中
            session.setAttribute("loginUser", one);
            return R.success("登录成功");
        } else {
            //登录失败
            return R.success("验证码错误");
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/loginout")
    public R logout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出登录成功");
    }

}
